package com.heima.homeservicemanagementsystem.controller;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.heima.homeservicemanagementsystem.entity.Apientity;
import com.heima.homeservicemanagementsystem.entity.UserAddress;
import com.heima.homeservicemanagementsystem.entity.common.OrderStatusEnum;
import com.heima.homeservicemanagementsystem.service.UserAddressService;
import com.heima.homeservicemanagementsystem.service.impl.AliPayServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.heima.homeservicemanagementsystem.entity.BuyrOrder;
import com.heima.homeservicemanagementsystem.service.BuyrOrderService;
import com.heima.homeservicemanagementsystem.mapper.BuyrOrderMapper;

import java.util.List;

import static cn.dev33.satoken.SaManager.log;

/**
 * 订单;(buyr_order)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-25
 */
@Slf4j
@Tag(name = "订单对象功能接口")
@RestController
@RequestMapping("/buyrOrder")
public class BuyrOrderController {
    @Resource
    private AliPayServiceImpl aliPayService;
    @Resource
    private BuyrOrderService buyrOrderService;

    @Resource
    private BuyrOrderMapper buyrOrderMapper;
    @Resource
    private UserAddressService userAddressService;

    @Operation(summary = "分页查询")
    @PostMapping("/page")
    public Result<Page<BuyrOrder>> paginQuery(@RequestBody PageParams<BuyrOrder> pageParams) {
        //查询参数
        BuyrOrder params = pageParams.getParams();
        LambdaQueryWrapper<BuyrOrder> lqw = new LambdaQueryWrapper<>();


        lqw.eq(params.getOrderId() != null, BuyrOrder::getOrderId, params.getOrderId());


        lqw.eq(params.getUserId() != null, BuyrOrder::getUserId, params.getUserId());


        lqw.eq(params.getAddressId() != null, BuyrOrder::getAddressId, params.getAddressId());


        lqw.eq(params.getTotalPrice() != null, BuyrOrder::getTotalPrice, params.getTotalPrice());


        lqw.eq(params.getPayablePrice() != null, BuyrOrder::getPayablePrice, params.getPayablePrice());


        lqw.eq(params.getPayMethod() != null, BuyrOrder::getPayMethod, params.getPayMethod());


        lqw.eq(params.getOrderStatus() != null, BuyrOrder::getOrderStatus, params.getOrderStatus());


        lqw.eq(params.getServiceId() != null, BuyrOrder::getServiceId, params.getServiceId());


        return Result.success(buyrOrderService.page(pageParams.getPage(), lqw));
    }


    @Operation(summary = "订单所有搜索")
    @GetMapping("/list")
    public Result searchQuery() {
        List<BuyrOrder> list = buyrOrderService.list();
        for (BuyrOrder order : list) {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("id", order.getAddressId());
            UserAddress one = userAddressService.getOne(wrapper);
            order.setUserAddress(one);

        }


        return Result.success(list);
    }

    @Operation(summary = "用户订单所有搜索")
    @GetMapping("/userlist")
    public Result usersearchQuery(@RequestParam String userid) {
        log.info("订单所有搜索：{}", userid);
        QueryWrapper<BuyrOrder> userId = new QueryWrapper<BuyrOrder>().eq(StringUtils.hasLength(userid), "user_id", userid);
        List<BuyrOrder> list = buyrOrderService.list(userId);
        for (BuyrOrder order : list) {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("id", order.getAddressId());
            UserAddress one = userAddressService.getOne(wrapper);
            order.setUserAddress(one);

        }


        return Result.success(list);
    }

    @Operation(summary = "通过服务id查询某种")
    @PostMapping("/Queryorderbyid")
    public Result Queryorderbyid(@RequestParam String userid, @RequestParam String orderstatus) {
        Result<List<BuyrOrder>> byServiceIdJson = buyrOrderService.findByServiceIdJson(userid, orderstatus);
        return byServiceIdJson;
    }

    @Operation(summary = "从业人员通过服务id查询所有的")
    @GetMapping("/searchorderbyid")
    public Result searchorderbyid(@RequestParam String userid) {
        Result<List<BuyrOrder>> byServiceIdJson = buyrOrderService.findByuserIdJson(userid);
        return byServiceIdJson;
    }

    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody BuyrOrder buyrOrder) {
        LambdaQueryWrapper<BuyrOrder> lqw = new LambdaQueryWrapper<>();


        lqw.eq(StringUtils.hasLength(buyrOrder.getId()), BuyrOrder::getId, buyrOrder.getId());


        lqw.eq(StringUtils.hasLength(buyrOrder.getOrderId()), BuyrOrder::getOrderId, buyrOrder.getOrderId());


        lqw.eq(StringUtils.hasLength(buyrOrder.getUserId()), BuyrOrder::getUserId, buyrOrder.getUserId());


        lqw.eq(StringUtils.hasLength(buyrOrder.getAddressId()), BuyrOrder::getAddressId, buyrOrder.getAddressId());


//        lqw.eq(StringUtils.hasLength(buyrOrder.getTotalPrice() ), BuyrOrder::getTotalPrice, buyrOrder.getTotalPrice());


//        lqw.eq(StringUtils.hasLength(buyrOrder.getPayablePrice()), BuyrOrder::getPayablePrice, buyrOrder.getPayablePrice());


        lqw.eq(StringUtils.hasLength(buyrOrder.getPayMethod()), BuyrOrder::getPayMethod, buyrOrder.getPayMethod());

        log.info("xinxi", buyrOrder.getOrderStatus() != null);
        if (OrderStatusEnum.isValidEnum(buyrOrder.getOrderStatus())) {
//            System.out.println("有效的枚举值");
            lqw.eq(StringUtils.hasLength(String.valueOf(buyrOrder.getOrderStatus())), BuyrOrder::getOrderStatus, buyrOrder.getOrderStatus());

        }


//        lqw.eq(StringUtils.hasLength(buyrOrder.getServiceId() ), BuyrOrder::getServiceId, buyrOrder.getServiceId());
        List<BuyrOrder> list = buyrOrderService.list(lqw);
        for (BuyrOrder order : list) {
            QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("id", order.getAddressId());
            UserAddress one = userAddressService.getOne(wrapper);
            order.setUserAddress(one);

        }


        return Result.success(list);
    }

    /**
     * 新增数据
     *
     * @param buyrOrder 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增数据")
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody BuyrOrder buyrOrder) throws BadRequestException {
        String s = buyrOrderService.createrOrder(buyrOrder);
        //        if(buyrOrderService.save(buyrOrder)){
//            return Result.success();
//        }
        if (StringUtils.hasLength(s)) {
            return Result.success(s);
        }
        return Result.error("下单失败");
    }

    @Operation(summary = "订单的取消")
    @PostMapping("/cancellationoforder")
    public Result cancellationoforder(@RequestBody BuyrOrder buyrOrder) throws BadRequestException, AlipayApiException, JsonProcessingException {

        BuyrOrder one = buyrOrderService.getOne(new QueryWrapper<BuyrOrder>().eq("id", buyrOrder.getId()));
        log.info("取消订单1:{}", one.getOrderStatus().getValue());
        log.info("取消订单:{}", one.getOrderStatus().getValue().equals(0));
        if (!one.getOrderStatus().getValue().equals(0)) {

            Apientity apientity = new Apientity();
            apientity.setTraceNo(buyrOrder.getId());
            apientity.setTotalAmount(String.valueOf(buyrOrder.getPayablePrice()));
            apientity.setSubject(buyrOrder.getServiceName().get(0));
            log.info("信息：{}", apientity);
            Result refund = aliPayService.refund(apientity);
            log.info("退款结果:{}", refund);
//            buyrOrderService.update(new UpdateWrapper<BuyrOrder>().lambda().set(BuyrOrder::getOrderStatus, OrderStatusEnum.Ordercompleted).eq(BuyrOrder::getId, buyrOrder.getId()));

        }
        buyrOrderService.update(new UpdateWrapper<BuyrOrder>().lambda().set(BuyrOrder::getOrderStatus, OrderStatusEnum.Ordercompleted).eq(BuyrOrder::getId, buyrOrder.getId()));
        return Result.success();

    }

    @Operation(summary = "通过id数据")
    @GetMapping("selectById")
    public Result<BuyrOrder> selectById(@RequestParam String id) {
        return Result.success(buyrOrderService.getById(id));
    }

    /**
     * 更新数据
     *
     * @param buyrOrder 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新数据")
    @PutMapping("update")
    public Result<Boolean> update(@RequestBody BuyrOrder buyrOrder) {
        log.info("更新状态;{}", buyrOrder);
        UpdateWrapper<BuyrOrder> objectUpdateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<BuyrOrder> eq = objectUpdateWrapper.lambda().set(buyrOrder.getOrderStatus() != null, BuyrOrder::getOrderStatus, buyrOrder.getOrderStatus()).eq(BuyrOrder::getId, buyrOrder.getId());

        if (buyrOrderService.update(eq)) {
            return Result.success();
        }
        return Result.error();
    }
//    @Operation(summary = "更新数据")
//    @PutMapping("update")
//    public Result<Boolean> update(@RequestBody BuyrOrder buyrOrder) {
//        log.info("更新状态;{}", buyrOrder);
//        UpdateWrapper<BuyrOrder> objectUpdateWrapper = new UpdateWrapper<>();
//        LambdaUpdateWrapper<BuyrOrder> eq = objectUpdateWrapper.lambda().set(buyrOrder.getOrderStatus() != null, BuyrOrder::getOrderStatus, OrderStatusEnum.Ordercompleted).eq(BuyrOrder::getId, buyrOrder.getId());
//        buyrOrderService.update(eq);
//        if (buyrOrderService.updateById(buyrOrder)) {
//            return Result.success();
//        }
//        return Result.error();
//    }


    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
            })
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteById(@PathVariable String id) {

        if (buyrOrderService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

    @Operation(summary = "多id删除数据")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (buyrOrderService.removeByIds(id)) {
            return Result.success();
        }
        return Result.error();
    }
}